#include "sfc_gd32wq.h"



uint8_t flash_read_status_reg1()
{
	uint8_t data;
	sfc_cmd_struct op = {0};
	FLASH_RD_STATUS_REG1(op);
	sfc_cmd_init(&op);
	sfc_flash_rd_reg(&data);
	return data;
}
uint8_t flash_read_status_reg2()
{
	uint8_t data;
	sfc_cmd_struct op = {0};
	FLASH_RD_STATUS_REG2(op);
	sfc_cmd_init(&op);
	sfc_flash_rd_reg(&data);
	return data;
}
uint8_t flash_read_status_reg3()
{
	uint8_t data;
	sfc_cmd_struct op = {0};
	FLASH_RD_STATUS_REG3(op);
	sfc_cmd_init(&op);
	sfc_flash_rd_reg(&data);
	return (uint8_t) data;
}
void flash_write_enable()
{
	sfc_cmd_struct op = {0};
	FLASH_WRITE_ENABLE(op);
	sfc_cmd_init(&op);
	sfc_flash_cmd_only();
}
void flash_write_disable()
{
	sfc_cmd_struct op = {0};
	FLASH_WRITE_DISABLE(op);
	sfc_cmd_init(&op);
	sfc_flash_cmd_only();
}
void flash_sector_erase(uint32_t addr)
{
	sfc_cmd_struct op = {0};
	do {
		flash_write_enable();
	} while(!(flash_read_status_reg1() & 0x2));
	FLASH_SECTOR_ERASE(op);
	sfc_cmd_init(&op);
	sfc_flash_erase(addr);
}
void flash_block_erase_32k(uint32_t addr)
{
	sfc_cmd_struct op = {0};
	do {
		flash_write_enable();
	} while(!(flash_read_status_reg1() & 0x2));
	FLASH_BLOCK_ERASE_32K(op);
	sfc_cmd_init(&op);
	sfc_flash_erase(addr);

}
void flash_block_erase_64k(uint32_t addr)
{
	sfc_cmd_struct op = {0};
	do {
		flash_write_enable();
	} while(!(flash_read_status_reg1() & 0x2));
	FLASH_BLOCK_ERASE_64K(op);
	sfc_cmd_init(&op);
	sfc_flash_erase(addr);
}
void flash_chip_erase()
{
	sfc_cmd_struct op = {0};
	do {
		flash_write_enable();
	} while(!(flash_read_status_reg1() & 0x2));
	FLASH_CHIP_ERASE(op);
	sfc_cmd_init(&op);
	sfc_flash_cmd_only();
}

ErrStatus flash_program(uint32_t xts_bypass, uint32_t addr, uint32_t data_bits, uint8_t *data)
{
	sfc_cmd_struct op = {0};
	do {
		flash_write_enable();
	} while(!(flash_read_status_reg1() & 0x2));
	FLASH_PAGE_PROGRAM(op);
	sfc_cmd_init(&op);
	return sfc_flash_pg(xts_bypass, addr, data_bits, data);
}

ErrStatus flash_read(uint32_t xts_bypass, uint32_t addr, uint32_t data_bits, uint8_t *data)
{
	sfc_cmd_struct op = {0};
	FLASH_READ_DATA(op);
	sfc_cmd_init(&op);
	return sfc_flash_rd(xts_bypass, addr, data_bits, data);
}

ErrStatus flash_fast_read(uint32_t xts_bypass, uint32_t addr, uint32_t data_bits, uint8_t *data)
{
	sfc_cmd_struct op = {0};
	FLASH_FAST_READ(op);
	sfc_cmd_init(&op);
	return sfc_flash_rd(xts_bypass, addr, data_bits, data);
}

ErrStatus flash_dual_output_fast_read(uint32_t xts_bypass, uint32_t addr, uint32_t data_bits, uint8_t *data)
{
	sfc_cmd_struct op = {0};
	FLASH_DUAL_OUTPUT_FAST_READ(op);
	sfc_cmd_init(&op);
	return sfc_flash_rd(xts_bypass, addr, data_bits, data);
}

ErrStatus flash_quad_output_fast_read(uint32_t xts_bypass, uint32_t addr, uint32_t data_bits, uint8_t *data)
{
	sfc_cmd_struct op = {0};
	FLASH_QUAD_OUTPUT_FAST_READ(op);
	sfc_cmd_init(&op);
	return sfc_flash_rd(xts_bypass, addr, data_bits, data);
}
